package com.czhhx.myedcon.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.aries.ui.view.title.TitleBarView;
import com.czhhx.myedcon.R;
import com.czhhx.myedcon.Tool.Algorithm;
import com.czhhx.myedcon.View.EcgView;
import com.czhhx.myedcon.entity.BaseDataEntity;
import com.czhhx.myedcon.entity.DataEntity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    /**
     * 声明控件变量
     */
    private EcgView mEcgView;
    private TextView th;
    private TextView u2;
    private TextView u3;
    private TextView u4;
    private TextView u5;
    private TextView f;
    private List<String> waveList = new ArrayList<>();
    float[] waveArray;
    boolean touched = false;
    private Handler mHandler = new Handler();
    private Runnable runnable;
    TitleBarView titleBar;
    private BaseDataEntity baseDataEntity;
    private DataEntity dataEntity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**
         * 根据控件找到布局id
         */
        f = findViewById(R.id.f_txt);
        mEcgView = findViewById(R.id.ecg_view);
        th = findViewById(R.id.thd_txt);
        u2 = findViewById(R.id.uo2_txt);
        u3 = findViewById(R.id.uo3_txt);
        u4 = findViewById(R.id.uo4_txt);
        u5 = findViewById(R.id.uo5_txt);
        titleBar = findViewById(R.id.titleBar);
        titleBar.setStatusBarLightMode(true);
        titleBar.setTitleMainText("首页");
        titleBar.setRightText("简介");
        titleBar.setTextColor(Color.parseColor("#000000"));
        /**
         * 点击进入简介
         */
        titleBar.setOnRightTextClickListener(view -> {
            Intent intent = new Intent(this, IntroductionActivity.class);
            startActivity(intent);
        });
        /**
         * 更新数据方法
         */
        upData();
    }

    public void upData() {
        /**
         * 定时器 每隔2秒执行一次
         */
        runnable = new Runnable() {
            @Override
            public void run() {
                /**
                 * 初始化数据方法
                 */
                initdata();
                /**
                 * 设置执行秒数
                 */
                mHandler.postDelayed(this, 2000);

            }
        };
        runnable.run();
    }

    private void initdata() {
        /**
         * 实体初始化
         */
        baseDataEntity = new BaseDataEntity();
        dataEntity = new DataEntity();
        /**
         * 根据接口请求数据
         */
        RequestParams params = new RequestParams("http://api.gzonehr.cn/data.php");
        /**
         * 接口传值
         */
        params.addParameter("action", "query");
        /**
         * 请求数据
         */
        x.http().request(HttpMethod.POST, params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                /**
                 * 成功返回数据result
                 *
                 */
                try {
                    /**
                     * 根据result解析数据到对象
                     */
                    JSONObject jsonObject = new JSONObject(result);
                    baseDataEntity.setMessage(jsonObject.getString("message"));
                    baseDataEntity.setResultCode(jsonObject.getInt("resultCode"));
                    JSONObject object = jsonObject.getJSONObject("data");
                    dataEntity.setF(object.getString("f"));
                    dataEntity.setHeart(object.getString("heart"));
                    dataEntity.setThdx(object.getString("thdx"));
                    dataEntity.setUo2(object.getString("uo2"));
                    dataEntity.setUo3(object.getString("uo3"));
                    dataEntity.setUo4(object.getString("uo4"));
                    dataEntity.setUo5(object.getString("uo5"));
                    baseDataEntity.setData(dataEntity);
                    initData(dataEntity);
                    initView(dataEntity);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            /**
             * 请求错误
             * @param ex
             * @param isOnCallback
             */
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(MainActivity.this, "网络错误请检查你的网络", Toast.LENGTH_LONG).show();
            }

            /**
             * 请求取消
             * @param cex
             */
            @Override
            public void onCancelled(CancelledException cex) {
            }

            /**
             * 请求完成
             */
            @Override
            public void onFinished() {
            }
        });

    }

    /**
     * 设置控件数据
     * @param entity
     */
    private void initData(DataEntity entity) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                th.setText("THDx：" + entity.getThdx() + "%");
                u2.setText("Uo2：" + entity.getUo2());
                u3.setText("Uo3：" + entity.getUo3());
                u4.setText("Uo4：" + entity.getUo4());
                u5.setText("Uo5：" + entity.getUo5());
                f.setText("f：" + entity.getF() + "Hz");
            }
        });
    }

    /**
     * 设置心率数据图数据
     * @param dataEntity
     */
    private void initView(DataEntity dataEntity) {
        waveList.add(dataEntity.getHeart() + "");
        waveArray = Algorithm.getFloats(waveList);
        LogUtil.e(waveList.toString());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mEcgView.setLeadData(waveArray);
            }
        });
        if (waveList.size()>=40){
            waveList.remove(0);
        }
    }

    /**
     * 当前界面销毁是清除定时器
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }


}